<?php

namespace app\admin\model;

use think\Model;

class Region extends Model
{
    public function Created($option)
    {
        if(count($option) === 0) {
            return Result(0, '数据输入不完全');
        }

        $id = $this->insertGetId($option);

        return Result(1, '添加成功', [
            'id' => $id
        ]);
    }

    public function DeleteById($id) {
        if ($this->where('id', $id)->count() == 1) {
            $this->where('id', $id)->delete();

            $this->where('parent_id', $id)->delete();
            return Result(1, '删除成功');
        }

        return Result(0, '提供的数据id不正确');
    }

    public function GetInfo($option)
    {
        $db = $this
            ->alias('r')
            ->field('r.*, p.name parent_name')
            ->join('region p', 'r.parent_id = p.id', 'LEFT');

        if (array_key_exists('id', $option) && $option['id'] !== '') {
            $db = $db->where('r.id', $option['id']);
        }

        if (array_key_exists('name', $option) && !empty($option['name'])) {
            $db = $db->whereLike('r.name', '%' . $option['name'] . '%');
        }
        
        $region = $db->find();
        if ($region) {
            return Result(1, '', [
                'region' => $region->toArray()
            ]);
        }
        return Result(0, '该地区不存在');
    }
    public function FindRegion($type, $account)
    {
        $region = $this
            ->alias('r')
            ->field('r.*, p.name parent_name')
            ->join('region p', 'r.parent_id = p.id', 'LEFT')
            ->where("r.{$type}", "{$account}")->find();

        if (!$region) {
            return Result(0, '该地区不存在');
        }
        return Result(1, '', [
            'region' => $region->toArray()
        ]);
    }
    
    public function ModifyData($id, $option) 
    {
        if ($this->where('id', $id)->count() == 1) {
            $this->where('id', $id)->data($option)->update();

            return Result(1, '修改成功');
        }

        return Result(0, '提供的数据id不正确');
    }

    public function GetList($page, $option)
    {
        $buildDb = function () use ($option) {
            $db = $this
                ->alias('r')
                ->field('r.*, p.name parent_name')
                ->join('region p', 'r.parent_id = p.id', 'LEFT');

            if (array_key_exists('name', $option) && !empty($option['name'])) {
                $db = $db->whereLike('r.name', '%' . $option['name'] . '%');
            }

            if (array_key_exists('parent_id', $option) && !empty($option['parent_id'])) {
                $db = $db->where('parent_id', $option['parent_id']);
            }

            return $db;
        };

        $count = $buildDb()->count();
        $list = $buildDb()->page($page, 50)->select();

        return Result(1, '', [
            'count' => $count,
            'list' => $list,
            'pageSize' => 50
        ]);
    }
}
